package com.zhuchang.self_rpc.test.democoding.nettydemo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;


/**
 * @Author RenPu
 * @Date 2022/2/9 11:31
 * @Version 1.0
 * @Description: 自定义业务逻辑处理，扩展使用（客户端的编码处理）
 **/
public class NettyClientHandler extends ChannelInboundHandlerAdapter {


    //当通道就绪时，就会触发此方法向服务端发送消息
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客戶端 client" +ctx);
        
        //写入缓存，并刷新到服务端channel
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, server: (￢︿̫̿￢☆)",CharsetUtil.UTF_8));

    }

    
    //读取服务端响应回来的数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf byteBuf=(ByteBuf)msg;
        System.out.println("从服务端接收的消息为："+byteBuf.toString(CharsetUtil.UTF_8));
        System.out.println("远程服务端的信息为："+ctx.channel().remoteAddress());
        ctx.channel().eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello, server: (￢︿̫̿￢☆)",CharsetUtil.UTF_8));
                    System.out.println("channel code=" + ctx.channel().hashCode());

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        ctx.channel().eventLoop().schedule(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                    ctx.writeAndFlush(Unpooled.copiedBuffer("hello, server: (￢︿̫̿￢☆)",CharsetUtil.UTF_8));
                    System.out.println("channel code=" + ctx.channel().hashCode());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },5, TimeUnit.SECONDS);

    }


    //当服务启动异常触发此方法
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.getCause(); //打印具体异常的信息
        ctx.close();  //释放资源
    }
}
